package redis

import (
	"github.com/gogf/gf/container/gmap"
	"github.com/gogf/gf/os/gcfg"
)

var (
	instances   = gmap.NewStrAnyMap(true)
	DefaultName = "default"
)

func NewClient(key string) *Redis {
	redisType := gcfg.Instance().GetString(key + ".type")
	if redisType != "node" && redisType != "cluster" {
		panic("redis type is error define!")
	}

	var conf RedisConf
	if redisType == "node" {
		conf.Host = gcfg.Instance().GetString(key + ".addr")
		conf.Type = redisType
		conf.Pass = gcfg.Instance().GetString(key + ".pass")
		conf.Tls = gcfg.Instance().GetBool(key + ".tls")

		return conf.NewRedis()
	} else {
		conf.Addrs = gcfg.Instance().GetStrings(key + ".addrs")
		conf.Type = redisType
		conf.Pass = gcfg.Instance().GetString(key + ".pass")
		conf.Tls = gcfg.Instance().GetBool(key + ".tls")

		return conf.NewRedis()
	}
	return conf.NewRedis()
}

// 容器封装
func Instance(name ...string) *Redis {
	key := DefaultName
	if len(name) > 0 && name[0] != "" {
		key = "redis.config." + name[0]
	} else {
		key = "redis.config." + key
	}
	return instances.GetOrSetFuncLock(key, func() interface{} {
		return NewClient(key)
	}).(*Redis)
}

// 客户端示例
func Client(name ...string) *Redis {
	return Instance(name...)
}
